package com.yugao.fintech.vctgone.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yugao.fintech.vctgone.admin.converter.RoleConverter;
import com.yugao.fintech.vctgone.admin.mapper.RoleMapper;
import com.yugao.fintech.vctgone.admin.pojo.dto.RoleDTO;
import com.yugao.fintech.vctgone.admin.pojo.po.SysRole;
import com.yugao.fintech.vctgone.admin.pojo.vo.RoleVO;
import com.yugao.fintech.vctgone.admin.service.RoleService;
import com.yugao.fintech.vctgone.mybatisplus.base.BaseQuery;
import com.yugao.fintech.vctgone.mybatisplus.util.PageUtil;
import com.yugao.fintech.vctgone.web.exception.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, SysRole> implements RoleService {
    private final RoleMapper roleMapper;
    private final RoleConverter roleConverter;

    @Override
    public PageUtil<RoleVO> getRoles(BaseQuery query) {
        PageUtil<SysRole> page = new PageUtil<>(query.getPageNum(), query.getPageSize());
        PageUtil<SysRole> roles = super.page(page, Wrappers.lambdaQuery(SysRole.class)
                .like(StrUtil.isNotBlank(query.getKeyWord()), SysRole::getName, query.getKeyWord())
                .or()
                .like(StrUtil.isNotBlank(query.getKeyWord()), SysRole::getRoleCode, query.getKeyWord())
                .select(SysRole::getId, SysRole::getName, SysRole::getRoleCode, SysRole::getRoleDesc)
        );
        return roleConverter.sysRolePageToRoleVoPage(roles);
    }

    @Override
    public void saveOrUpdate(RoleDTO dto) {
        super.saveOrUpdate(roleConverter.roleDtoToSysRole(dto));
    }

    @Override
    public void deleteRole(String ids) {
        if (StrUtil.isBlank(ids)) {
            throw new BadRequestException("ids 不能为空");
        }
        Set<Long> idSet = Arrays.stream(ids.split(",")).map(Long::valueOf).collect(Collectors.toSet());
        super.removeByIds(idSet);
    }

    @Override
    public List<SysRole> listRoleByUserId(Long id) {
        return roleMapper.listRoleByUserId(id);
    }

    @Override
    public List<SysRole> listRoleByUserName(String username) {
        return roleMapper.listRoleByUsername(username);
    }

    @Override
    public List<RoleVO> getAllRoles() {
        List<SysRole> sysRoleList = super.list(Wrappers.lambdaQuery(SysRole.class)
                .select(SysRole::getId, SysRole::getName, SysRole::getRoleCode, SysRole::getRoleDesc));
        return roleConverter.sysRoleListToRoleVoList(sysRoleList);
    }
}
